//
//  BaseViewController.m
//  WelfareManager
//
//  Created by timtian on 16/12/23.
//  Copyright © 2016年 timtian. All rights reserved.
//


#import "BaseViewController.h"
#import "BaseInfoController.h"

#import "BackBtn.h"
#import "UIImage+Color.h"

@interface BaseViewController ()<UIGestureRecognizerDelegate>

@property(nonatomic, strong) UITapGestureRecognizer *singleTapGR;



@end

@implementation BaseViewController
#pragma mark - 生命周期
-(void)dealloc{
    NSLog(@"%@---dealloc",[self class]);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    
    BaseViewController *vc = [super allocWithZone:zone];
//    @weakify(vc);
//    [[vc rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(RACTuple * _Nullable x) {
//       
//        @strongify(vc);
//        [vc lm_addSubviews];
//        [vc lm_bindViewModel];
//        [vc lm_layoutNavigation];
//    }];
    
//    [[vc rac_signalForSelector:@selector(viewDidLayoutSubviews)] subscribeNext:^(RACTuple * _Nullable x) {
//       
//        @strongify(vc);
//        [vc lm_layoutSubviews];
//    }];
    
//    [[vc rac_signalForSelector:@selector(updateConstraints)] subscribeNext:^(RACTuple * _Nullable x) {
//       
//        @strongify(vc);
//        [vc lm_updateConstraints];
//    }];
    
//    [[vc rac_signalForSelector:@selector(viewWillAppear:)] subscribeNext:^(RACTuple * _Nullable x) {
//       
//        @strongify(vc);
//        [vc lm_getNewData];
//    }];
    
    return vc;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.allowPopGesture = YES;
    [UIApplication sharedApplication].statusBarHidden = false;
    //设置状态栏白色字体
   [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;    
    
    [self.view addSubview:self.navigationBar];
    [self.navigationBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
        make.height.mas_equalTo(64);
    }];
    
    self.showNav = YES;
    
    self.view.backgroundColor = kBGColor;

    if (self.navigationController.viewControllers.count >1 ) {
        BackBtn * button=[[BackBtn alloc] init];
        button.frame=CGRectMake(0, 0, 50, 21);
        
        [button addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:button];
        
        [self setLeftBarButtonItem:backItem];
//        self.navItem.backBarButtonItem = backItem;
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self lm_addSubviews];
    [self lm_bindViewModel];
    [self lm_layoutNavigation];
    [self lm_getNewData];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setUpForDismissKeyboard];
    NSLog(@"%@",[self class]);
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    //注册屏幕旋转 消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(changeFrames:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];

    
}



//收到通知后改变view坐标

-(void)changeFrames:(NSNotification *)notification{
    
    
    if ([[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortrait
        
        || [[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortraitUpsideDown){
        NSLog(@"portrait");
        
        [self setVerticalFrame];
    }else{
        NSLog(@"横屏");
        [self setHorizontalFrame];
    }
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self lm_layoutSubviews];
}

- (void)updateViewConstraints {
    [super updateViewConstraints];
    [self lm_updateConstraints];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = self.isAllowPopGesture;
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = !self.isAllowPopGesture;
    
}

#pragma mark -- Public
-(void)setVerticalFrame{
    
    
}
-(void)setHorizontalFrame{
    
    
}

#pragma mark - set方法和get方法

-(UINavigationBar *)navigationBar {
    if (_navigationBar == nil) {
        _navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 64)];
        _navigationBar.items = @[self.navItem];
        _navigationBar.titleTextAttributes = @{
                                               NSFontAttributeName : [UIFont systemFontOfSize:18],
                                               NSForegroundColorAttributeName : [UIColor whiteColor]
                                               };
        [_navigationBar setBackgroundImage:[UIImage lm_imageWithColor:kColor4B79AF]
                             forBarMetrics:UIBarMetricsDefault];
        [_navigationBar setShadowImage:[UIImage lm_imageWithColor:kColor4B79AF]];
    }
    return _navigationBar;
}

-(UINavigationItem *)navItem {
    if (_navItem == nil) {
        _navItem = [[UINavigationItem alloc] init];
    }
    return _navItem;
}

-(void)setShowNav:(BOOL)showNav {
    _showNav = showNav;
    
    self.navigationBar.hidden = !showNav;
}

#pragma mark - IBActions

//点击屏幕键盘消失
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    
    [nc addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [nc addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)keyboardWillShow:(NSNotification *)aNotification
{
    if (self.singleTapGR == nil) {
        self.singleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)];
    }
    [self.view addGestureRecognizer:self.singleTapGR];
}

-(void)keyboardWillHide:(NSNotification *)aNotification
{
    [self.view removeGestureRecognizer:self.singleTapGR];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}
#pragma mark - Public

- (void)createUI {
    
}

- (void)setLayout {
    
}

- (void)lm_addSubviews{}
- (void)lm_bindViewModel{}
- (void)lm_layoutNavigation{}
- (void)lm_layoutSubviews{}
- (void)lm_updateConstraints{}
- (void)lm_getNewData{}


-(void)setLeftBarButtonItem:(UIBarButtonItem *)barButtonItem {
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -2.5;
    //替换方法
    
    if (!barButtonItem) {
        self.navItem.leftBarButtonItems = nil;
        return;
    }
    
    if (barButtonItem.title.length) {
        barButtonItem.title = [NSString stringWithFormat:@"%@",barButtonItem.title];
    }
    
    self.navItem.leftBarButtonItems = @[negativeSpacer,barButtonItem];
}

-(void)setRightBarButtonItem:(UIBarButtonItem *)barButtonItem {

    //替换方法
    
    if (!barButtonItem) {
        self.navItem.rightBarButtonItems = nil;
        return;
    }
    
    if (barButtonItem.title.length) {
        barButtonItem.title = [NSString stringWithFormat:@"  %@",barButtonItem.title];
    }
    
    [self setRightItems:@[barButtonItem]];
    
}

- (void)setRightItems:(NSArray *)items {
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -2;
    NSMutableArray *items2 = [NSMutableArray arrayWithArray:items];
    [items2 insertObject:negativeSpacer atIndex:0];
    
    self.navItem.rightBarButtonItems = items2;
}

#pragma mark - Private
//返回事件，两种方法都要写
-(void)backAction
{
    
    [self.navigationController popViewControllerAnimated:YES];

}



//设置导航栏上的标题
- (void)setTitle:(NSString *)title {
    
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:18];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.lineBreakMode=NSLineBreakByTruncatingTail;
    titleLabel.text = title;
    [titleLabel sizeToFit];
    titleLabel.centerX = __kScreenWidth * 0.5;
    titleLabel.centerY = 22;
    
    self.navItem.titleView = titleLabel;
    
}

#pragma mark --  Public
//圆角
+(void)getRoundIcon:(id)sender borderWidth:(float)borderWidth borderColor:(UIColor *)borderColor  cornerRadius:(float)cornerRadius
{
    UIView *view = (UIView *)sender;
    
    if (borderWidth < .5) {
        borderWidth = .5;
    }
    
    view.layer.borderWidth = borderWidth;
    view.layer.cornerRadius = cornerRadius;
    view.layer.borderColor = borderColor.CGColor;
    view.layer.masksToBounds = YES;
}


+(NSString *)stringFromDate:(NSDate *)date
{
    NSString *string = @"";
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    string = [formatter stringFromDate:date];
    if (!string) {
        return @"0000-00-00 00:00";
    }
    
    string = [[string componentsSeparatedByString:@" "] objectAtIndex:0];
    
    return string;
}

+(NSString *)stringFromHHMMDate:(NSDate *)date{
    NSString *string = @"";
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    string = [formatter stringFromDate:date];
    if (!string) {
        return @"0000-00-00 00:00";
    }
    
    string = [[string componentsSeparatedByString:@" "] objectAtIndex:1];
    
    return string;
}


/**
 *获取当天是星期几
 */
+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}

- (void)addUnitIDAndStationno {
    
    BaseInfoController *vc = [[BaseInfoController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
    
//    [MBProgressHUD showText:@"处理stationno和unit_id的问题" onView:nil];
}

#pragma mark - 数据源和代理方法

#pragma mark - UIView -> 下面放继承自UIView的方法




@end
